﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace CSharpExerciseAndExperiment.ExA
{

    /// <summary>
    /// A2.xaml 的交互逻辑
    /// </summary>

    class Scan
    {
        public IPAddress strip;
        public string hostname;
        public string scantime;
        public void CheckComputer()
        {
            DateTime begintime=DateTime.Now;

            try
            {
                IPHostEntry iphost = Dns.GetHostEntry(strip);
                hostname = iphost.HostName.ToString();
            }
            catch
            {
                hostname = "";
            }
            finally {
                DateTime endtime = DateTime.Now;
                scantime = (endtime - begintime).TotalMilliseconds.ToString();
            }
        }
        
    }

    public partial class A2 : Page
    {
        private int state = 0;//正常
        private int ipCount;//待扫描的IP总数
        string[] readyToCheck;//待检测的IP字符串
        IPAddress[] ipAddress;//已经生成的IPAddress数组
        double[] taskTime;//扫描时间
        int n;//循环递减的计数变量
        public A2()
        {
            InitializeComponent();
            IPAddressPer.Text = "172.20.66.";
            IPAddressBegin.Text = "1";
            IPAddressEnd.Text = "100";
        }
        
        public void CheckComputer(Object strip)
        {
            DateTime begintime = DateTime.Now;
            string hostname="";
            string scantime;
            try
            {
                IPHostEntry iphost = Dns.GetHostEntry(strip.ToString());
                hostname = iphost.HostName.ToString();
            }
            catch
            {
                hostname = "";
            }
            finally
            {
                DateTime endtime = DateTime.Now;
                scantime = (endtime - begintime).TotalMilliseconds.ToString();
                AddStatusInfoToListBox(strip.ToString(),scantime,hostname);
                n--;
                if (n == 0)
                {
                    String s1 = "";
                    for (int i = 0; i < scanmsg.Items.Count; i++)
                    {
                        String s = scanmsg.Items[i].ToString();
                        s1 = CompareNumber(s, i);
                    }

                    DateTime taskEnd = DateTime.Now;
                    TimeSpan taskAll = taskEnd - begintime;
                    MessageBox.Show("扫描完毕！总用时：" + taskAll.TotalMilliseconds + "毫秒" + s1);

                }
            }
        }
        
        private void MutBiginScanBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ipCount =1+ int.Parse(IPAddressEnd.Text) - int.Parse(IPAddressBegin.Text);
                n = ipCount;
                taskTime = new double[ipCount];//扫描时间数组
                readyToCheck = new string[ipCount];
                ipAddress = new IPAddress[ipCount];
                for (int i = 0; i < ipCount; i++)
                {
                    readyToCheck[i] = IPAddressPer.Text + (int.Parse(IPAddressBegin.Text)+i).ToString();
                    ipAddress[i] = IPAddress.Parse(readyToCheck[i]);
                }
            }
            catch (Exception)
            {
                errormsg.Text = "请输入正确的IP地址！";
                errormsg.Height = 20;
                scanmsg.Dispatcher.Invoke(() =>scanmsg.Items.Add( "IP地址有错！"));
                state = 1;
            }
            if (state == 0)
            {
                SingleBiginScanBtn.IsEnabled = false; //设置按钮为不可点击状态
                MutBiginScanBtn.IsEnabled = false;

                Thread[] scanThreads = new Thread[ipCount];
                Scan scanObj = new Scan();//定义Scan实例
                for (int i = 0; i <ipCount; i++)
                { 
                                      
                    //初始化线程实例
                    scanThreads[i] = new Thread(CheckComputer);
                    //启动线程
                    scanThreads[i].Start(ipAddress[i]);
                   
                }
            }
        }

        private void SingleBiginScanBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ipCount =1+ int.Parse(IPAddressEnd.Text) - int.Parse(IPAddressBegin.Text);
                readyToCheck = new string[ipCount];
                ipAddress = new IPAddress[ipCount];
                for (int i = 0; i < ipCount; i++)
                {
                    readyToCheck[i] = IPAddressPer.Text + (int.Parse(IPAddressBegin.Text) + i).ToString();
                    ipAddress[i] = IPAddress.Parse(readyToCheck[i]);
                }
            }
            catch (Exception)
            {
                errormsg.Text = "请输入正确的IP地址！";
                errormsg.Height = 20;
                scanmsg.Dispatcher.Invoke(() => scanmsg.Items.Add("IP地址有错！"));
                state = 1;
            }
            if (state == 0)
            {
                SingleBiginScanBtn.IsEnabled = false; //设置按钮为不可点击状态
                MutBiginScanBtn.IsEnabled = false;

                Thread[] scanThreads = new Thread[ipCount];
                for (int i = 0; i <ipCount; i++)
                {
                    //定义Scan实例
                    Scan scanObj = new Scan();
                    scanObj.strip = ipAddress[i];
                    scanObj.CheckComputer();
                    AddStatusInfoToListBox(scanObj.strip.ToString(),scanObj.scantime, scanObj.hostname);
                }
            }
        }

        //重置
        private void resetBtn_Click(object sender, RoutedEventArgs e)
        {
            state = 0;
            SingleBiginScanBtn.IsEnabled = true; //设置按钮为可点击状态
            MutBiginScanBtn.IsEnabled = true;
            scanmsg.Items.Clear();
            errormsg.Text = "";
            errormsg.Height = 0;
        }

        //向scanmsg添加信息
        public void AddStatusInfoToListBox(string strip,string scantime,string hostname)
        {
            scanmsg.Dispatcher.Invoke(() => scanmsg.Items.Add("IP地址：" + strip + ",扫描用时" + scantime + "毫秒,主机名：" + (hostname == "" ? "(不在线)" : hostname) + "\n"));
        }

        //进行比较
        private String CompareNumber(String s, int i)
        {
            int P1 = s.IndexOf('时');//取scantime头
            int P2 = s.IndexOf('毫');//取scantime尾
            int start = P1 + 1;
            int length = P2 - P1 - 1;
            double maxTime = 0;
            double minTime = 0;
            

            String s2 = s.Substring(start, length);
            taskTime[i] = double.Parse(s2);
            if (i == (taskTime.Length - 1))
            {
                maxTime = taskTime[0];
                minTime = taskTime[0];
                for (int p = 0; p < taskTime.Length; p++)
                {
                    if (maxTime < taskTime[p])
                    {
                        maxTime = taskTime[p];
                    }
                }
                for (int p = 0; p < taskTime.Length; p++)
                {
                    if (minTime > taskTime[p])
                    {
                        minTime = taskTime[p];
                    }
                }
            }
            return "最长时间为：" + maxTime + "毫秒，最短时间为:" + minTime+"毫秒。";

        }
    }
}
